from django.template import Library
from types import FunctionType

register = Library()


def head_list(cl):
    """表头数据"""
    if cl.list_display:
        for name_or_func in cl.list_display:
            # 定制功能（checkbox, edit, del.....）
            if isinstance(name_or_func, FunctionType):
                # 表头第一列
                verbose_name = name_or_func(cl.config, header=True)
            else:
                # 获取表头其他列的标题
                verbose_name = cl.config.model_class._meta.get_field(name_or_func).verbose_name
            yield verbose_name
    else:
        yield cl.config.model_class._meta.model_name


def body_list(cl):
    """表格数据"""
    for row in cl.queryset:
        data_list = []
        if not cl.list_display:
            # 没有标题就以数据对象为标题数据
            data_list.append(row)
            yield data_list
            continue

        for name_or_func in cl.list_display:
            if isinstance(name_or_func, FunctionType):
                # 定制功能（checkbox, edit, del.....）
                val = name_or_func(cl.config, row=row)
            else:
                # 其他列数据
                val = getattr(row, name_or_func)
            data_list.append(val)
        yield data_list


@register.inclusion_tag("stark/table.html")
def table(cl):
    return {"head_list": head_list(cl), "body_list": body_list(cl)}
